﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace DynamicListView.Controls
{
public class ListViewExtension
{
    /// <summary>
    /// MatrixSource Attached Dependency Property
    /// </summary>
    public static readonly DependencyProperty MatrixSourceProperty =
        DependencyProperty.RegisterAttached("MatrixSource",
        typeof(DataMatrix), typeof(ListViewExtension),
            new FrameworkPropertyMetadata(null,
                new PropertyChangedCallback(OnMatrixSourceChanged)));

    /// <summary>
    /// Gets the MatrixSource property.  
    /// </summary>
    public static DataMatrix GetMatrixSource(DependencyObject d)
    {
        return (DataMatrix)d.GetValue(MatrixSourceProperty);
    }

    /// <summary>
    /// Sets the MatrixSource property.  
    /// </summary>
    public static void SetMatrixSource(DependencyObject d, DataMatrix value)
    {
        d.SetValue(MatrixSourceProperty, value);
    }

    /// <summary>
    /// Handles changes to the MatrixSource property.
    /// </summary>
    private static void OnMatrixSourceChanged(DependencyObject d,
        DependencyPropertyChangedEventArgs e)
    {
        ListView listView = d as ListView;
        DataMatrix dataMatrix = e.NewValue as DataMatrix;

        listView.ItemsSource = dataMatrix; 
        GridView gridView = listView.View as GridView; 
        int count = 0; 
        gridView.Columns.Clear();
        foreach (var col in dataMatrix.Columns)
        {
            gridView.Columns.Add(
                new GridViewColumn
                    {
                        Header = col.Name,
                        DisplayMemberBinding = new Binding(string.Format("[{0}]", count))
                    }); 
            count++;
        }
    }
}
}